summaryrefslogtreecommitdiff
path: root/src/explicitsimulation.h
blob: c2aeed9786438ea5edca97a1e0def33947b0c173 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef GENETIC_EXPLICIT_SIMULATION_H
#define GENETIC_EXPLICIT_SIMULATION_H

#include "genetic/population.h"
#include "genetic/config.h"

#include <bu/thread.h>
#include <bu/mutex.h>
#include <bu/synchroqueue.h>

namespace Genetic
{
	class Operator;
	class FitnessFunction;

	class ExplicitSimulation
	{
	public:
		ExplicitSimulation( Operator *pOper, FitnessFunction *pFunc,
				int iThreads, int iPopSize, float fKeep, float fRandom,
				bool bKeepBest=true );
		virtual ~ExplicitSimulation();

		void timestep();

		Genetic::PhenotypeId selectWeighted();

		double getMinFitness() const { return dMinFitness; }
		double getMaxFitness() const { return dMaxFitness; }

	protected:
		void updateFitness();
		void setFitness( Genetic::PhenotypeId, double dFitness );

	protected:
		Population xPop;
		Operator *pOper;

	private:
		int iPopSize;
		float fKeep;
		float fRandom;
		bool bKeepBest;
		typedef Bu::Hash<Genetic::PhenotypeId, double> FitnessHash;
		FitnessHash hFitness;
		double dMinFitness;
		double dMaxFitness;
		double dTotalFitness;
		PhenotypeId uMaxFitness;

		Bu::Mutex mFitness;
		typedef Bu::SynchroQueue<Phenotype *> WorkQueue;
		WorkQueue qWork;

		class Processor : public Bu::Thread
		{
		public:
			Processor( ExplicitSimulation &rSim, FitnessFunction *pFunc,
					WorkQueue &rqWork, int iId );
			virtual ~Processor();

			void setRunning( bool b ) { bRunning = b; }

		protected:
			virtual void run();

			ExplicitSimulation &rSim;
			FitnessFunction *pFunc;
			WorkQueue &rqWork;
			int iId;
			bool bRunning;
		};

		typedef Bu::List<Processor *> ProcessorList;
		ProcessorList lProcessor;
	};
};

#endif